package com.ncst.newsfragment;


import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.ncst.coursecode.R;

import java.util.List;

public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
    List<News> newsList;
    boolean isTwoPane;
    FragmentActivity activity;

    public NewsAdapter(List<News> newsList, boolean isTwoPane, FragmentActivity activity) {
        this.newsList = newsList;
        this.isTwoPane=isTwoPane;
        this.activity=activity;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull final ViewGroup viewGroup, int i) {
        View view=LayoutInflater.from(viewGroup.getContext()).
                inflate(R.layout.news_item,viewGroup,false);
        ViewHolder viewHolder=new ViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
        News news=newsList.get(i);
        viewHolder.tvNewsTitle.setText(news.getTitle());

        final String newsTitle=news.getTitle();
        final String newsContent=news.getContent();
        View view=viewHolder.itemView;
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isTwoPane){
                    NewsContentFragment contentFragment=(NewsContentFragment) activity
                            .getSupportFragmentManager()
                            .findFragmentById(R.id.news_content_fragment);
                    contentFragment.refresh(newsTitle,newsContent);
                }else{
                    //启动newscontent活动
                    NewsContentActivity.actionStart(activity,newsTitle,newsContent);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return newsList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        TextView tvNewsTitle;

        public ViewHolder(@NonNull View view) {
            super(view);
            tvNewsTitle=view.findViewById(R.id.news_title);
        }
    }
}
